package com.cloud.sample.controller;

import com.cloud.common.bean.ResultInfo;
import com.cloud.common.util.JsonUtils;
import com.cloud.sample.dto.WechatSignDTO;
import com.cloud.sample.dto.WxMpTemplateMsgParamDTO;
import com.cloud.sample.provider.WechatProvider;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 微信接口
 */
@Slf4j
@RestController
public class WechatController {
    @Autowired
    private WechatProvider wechatProvider;

    @Autowired
    private WxMpService wxMpService;

    /**
     * 发送微信公众号模板消息
     *
     * @param paramDTO
     * @return ResultInfo<String>
     * @throws Exception
     */
    @PostMapping("/wechat/sendMpTemplateMsg")
    public ResultInfo<String> sendMpTemplateMsg(@Valid @RequestBody WxMpTemplateMsgParamDTO paramDTO) throws Exception {
        List<WxMpTemplateData> paramDataList = new ArrayList<>();
        Map<String, String> paramMap = JsonUtils.parseObject(paramDTO.getJsonParamData(), Map.class);
        Iterator<String> iterator = paramMap.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            paramDataList.add(new WxMpTemplateData(key, paramMap.get(key)));
        }
        WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage();
        wxMpTemplateMessage.setTemplateId(paramDTO.getTemplateId());
        wxMpTemplateMessage.setData(paramDataList);
        wxMpTemplateMessage.setUrl(paramDTO.getUrl());
        wxMpTemplateMessage.setToUser(paramDTO.getToUser());

        // 发送模板消息
        String msgId = wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
        log.info("sendMpTemplateMsg msgId={}", msgId);

        return ResultInfo.success();
    }

    /**
     * 获取签名
     *
     * @param url
     * @return
     */
    @GetMapping("/wechat/getSignature")
    public ResultInfo<WechatSignDTO> get(String url) {
        return ResultInfo.success().setData(wechatProvider.getSignature(url));
    }
}
